package tech.realcpf.duckengine1.duckdb;

import org.duckdb.DuckDBConnection;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.realcpf.duckengine1.util.ResultUtil;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

public class DuckDbInstanceTest {
    private static final Logger LOGGER = LoggerFactory.getLogger(DuckDbInstanceTest.class);
    private static final DuckDBConnection conn;
    static {
        Properties prop = new Properties();
        try {
            conn = DuckDBConnection.newConnection("jdbc:duckdb:demo1",false,prop);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) throws IOException {
        Terminal terminal = TerminalBuilder.terminal();
        LineReader lineReader = LineReaderBuilder.builder()
                .terminal(terminal)
                .build();
        List<String> sql = new LinkedList<>();
        sql.add("SET s3_url_style='path';SET s3_use_ssl=false;");
//        sql.add("SET s3_url_style='path';");
//        sql.add("SET s3_endpoint='192.168.124.87:9000';");
//        sql.add("SET s3_access_key_id='admin' ;");
//        sql.add("SET s3_secret_access_key='password';");
//        sql.add("SET s3_use_ssl=false;");

        init(sql);
        String line;
        StringBuffer buffer = new StringBuffer();
        while (!"quit".equals(line = lineReader.readLine(">"))) {
            buffer.append(line);
            if (line.endsWith(";")) {
                execWithPrint(buffer.toString());
                buffer.setLength(0);
            } else {
                System.out.println(">");
            }
        }
    }

    private static void init(List<String> sql) {
        for (String s:sql) {
            execWithPrint(s);
        }
    }

    private static void execWithPrint(String sql) {
        LOGGER.info(sql);
        try(PreparedStatement ps = conn.prepareStatement(sql)) {
            if (ps.execute()) {
                ResultSet rs = ps.getResultSet();
                ResultUtil.print(rs);
            }

        }catch (Exception e) {
            LOGGER.error("error when exec sql {}",sql);
        }
    }
}
